import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.hp.util.IOUtil;
import com.hp.util.JsonUtil;
import com.hp.util.MapUtil;
import com.hp.util.PropUtil;
import com.hp.util.XmlUtil;

public class GateTest {

	public static void main(String[] args) throws IOException, DocumentException {
		try {
			new GateTest().InStream();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	
	
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	public void InStream() throws Exception{
		// TODO Auto-generated method stub
				String conf = "add";//访问handler时带进来的参数  比如http://localhost:8080/gate/query?conf=add
				//获取配置文件
				
				String encode=PropUtil.getPropByKey(conf,"encode")==null?"UTF-8":PropUtil.getPropByKey(conf,"encode");
				String root=PropUtil.getPropByKey(conf,"root")==null?"DATA":PropUtil.getPropByKey(conf,"root");
				File f = new File("D:/bb.txt");
				//模拟读取流
				InputStream in = new FileInputStream(f);
				
				String instr = IOUtil.getStringByIn(in,encode); //输入的
				System.out.println("接收到的流为 :"+"\n"+instr);
				Map<String,Object> map = null;
				
				
				if(instr.startsWith("{")){//json
					System.out.println("接收到的流类型为:json");
					map = JsonUtil.json2Map(instr);
				}else if(instr.startsWith("<")){
					System.out.println("接收到的流类型为:xml");
					map = XmlUtil.xml2Map(instr);
				}else{
					System.out.println("接收到的流类型为:不知道error");
					//.....其他情况
				}
				System.out.println("转换前的map为:"+map);
				
				Map tmplatemap = new MapUtil().genMapByXmlTemplate("add.xml",map);
				
				System.out.println("转换后的map为:"+tmplatemap);
				
//				String ts[] = {"persons","person"};
//				String ts1[] = {"place","pro"};
//				Object obj = getValueByKeys(map,ts1);//根据指定的persons.person得到的结果
//				//如果是list则把list里的map的key值转换了
//				if(obj instanceof List){
//					List list = mappedListByKey((List) obj,"name=xm,age=nl");
//					System.out.println(list);
//				}
				
	//			haha(map);
				
				//Map 业务处理开始.........
	//			Map resmap = new HashMap();
//				resmap=createMapByStr("xsm.xs.xm");
//				System.out.println("resmap:"+resmap);
		//		tt(map);
				
//				Map mapt = new HashMap();
//				List ulist = new ArrayList();
//				Map user = new HashMap();
//				user.put("NAME","zhao");
//				user.put("AGE","20");
//				Map mapU = new HashMap();
//				mapU.put("user", user);
//				ulist.add(mapU);
//				Map user1 = new HashMap();
//				user1.put("NAME","qian");
//				user1.put("AGE","26");
//				Map mapU1 = new HashMap();
//				mapU1.put("user", user1);
//				ulist.add(mapU1);
//				mapt.put("users",ulist);
				
				
				//业务处理结束  开始输出
				String outXml = XmlUtil.map2Xml(tmplatemap, encode,root);
				String outJson = JsonUtil.map2Json(tmplatemap);
				System.out.println("输出的xml为:"+outXml);
				System.out.println("输出的json为:"+outJson);
//				
//				Map p = JsonUtil.json2Map("");
//				System.out.println(p);
//				
////				System.out.println(instr);
//				Map m = XmlUtil.xml2Map(instr);
//				System.out.println(m);
//				
//				System.out.println(JsonUtil.map2Json(m));;
//				
//				String str = XmlUtil.mapToXml(m,encoding);
//				System.out.println(str);
//				
//				System.out.println(XmlUtil.xml2Map(str));
//				
//				Map map = null;
//				//判断字符串的开头 如果{为json  如果<为xml   判断为空
//				
//				
//				System.out.println(map);
				
//				ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
//				
//				
		//
//				BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
//				Document doc = new SAXReader().read(br);
//				Element root = doc.getRootElement();
//				Element _logicName = (Element) root.selectSingleNode("LOGIC/LOGICNAME");
//				String logicName = _logicName.getText();
//				System.out.println(logicName);
				
	}
	
	
	
	
	
	
	
	
	
	
	
	public Map filedMapped(Map map){
		
		Map<String, String> all = PropUtil.getAllProp("add_filed");
		
		for(String key:all.keySet()){
			System.out.println("key:"+key+" value:"+all.get(key));
		}

		return map;
	}
	
	
	public Map test(Map map){
		
		
		
		return map;
	}
	
	
	@SuppressWarnings("rawtypes")
	public Map getMapByjd(Map map,String t[],String key){
		
		for(int i=0;i<t.length;i++){
			Object obj =  map.get(t[i]);
			if(obj==null || obj instanceof String)
				return new HashMap();
			
			System.out.println("obj:"+obj);
			map = (Map) obj;
			if (t[i].equals(key) )
					break;
		}
		return map;
	}
	
	
	
	static String keyl = "";
	static String upLev = "";
	static boolean clean=false;
	public static void haha(Map<String,Object> map){
		
		for(String key:map.keySet()){
			
			if(!upLev.equals("list") && clean){
				keyl="";
			}
			
			if(keyl.equals("")){
				keyl=key;
			}else{
				keyl=keyl+"."+key;
			}
			System.out.println("keyl:"+keyl);
			Object obj = map.get(key);
			System.out.println(key+" "+obj);
			
			if(obj instanceof Map){
				Map p = (Map) obj;
				upLev="map";
				haha(p);
				
			}else if(obj instanceof List){
				List list = (List) obj;
				for(int i=0;i<list.size();i++){
					obj = list.get(i);
					upLev="list";
					if(obj instanceof Map){
						Map p = (Map) obj;
						haha(p);
					}else{
						//最后一层 下面没有了则清空
						System.out.println("keyl:"+keyl);
						System.out.println(key+" "+obj);
						if(upLev.equals("list") && list.size()==i+1){
							keyl=keyl.substring(0,keyl.lastIndexOf("."));
						}else{
							clean=true;
						}
//						if(key.equals("ddd"))
//							map.put(key,"666666");
					//	System.out.println("objooo"+obj);
					}
				}
			}else{
				
				//最后一层 下面没有了则清空
				if(upLev.equals("list")){
					keyl=keyl.substring(0,keyl.lastIndexOf("."));
				}else{
					clean=true;
				}
//				if(key.equals("ddd"))
//					map.put(key,"666666");
			//	System.out.println("objooo"+obj);
			}
		}
	}
	
	
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map createMapByStr(String targetfiled){
		
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> fileds = PropUtil.getAllProp("add_filed");
		
		for(String k:fileds.keySet()){
			targetfiled=fileds.get(k);
			String t[] = targetfiled.split("\\.");
			Map last = null;
			for(int i=t.length;i>0;i--){
				String key = t[i-1];
				
				System.out.println("第几次:"+i+key);
				Map<String,Object> tm = new HashMap<String, Object>();
				Map<String,Object> tm1 = new HashMap<String, Object>();
				
				if(i!=1 && t.length>1)
					tm=getMapByjd(map,t,t[i-2]);
				
				if(last!=null){
					List list = new ArrayList();
					if(key.endsWith("*")){
						list.add(last);
						tm.put(key.substring(0,key.length()-1), list);
					}else{
						tm.put(key,last);
					}
				}
				else{
					tm1.put(key,key);
					tm.put(key,key);
				}
				last=tm;
			//	map.put(t[i-1],"");
			}
			System.out.println(last);
			map=last;
		}
//		targetfiled="xsm.xs.nl";
		
		return map;
//		Map map3 = new HashMap();
//		map3.putAll(map);
//		map3.putAll(last);
//		
//		Map map4 = new HashMap();
//		Map ddd = new HashMap();ddd.put("ddd","ddd");
//		Map ccc = new HashMap();ccc.put("ccc","ccc");
//		map4.put("1",ddd);
//		map4.put("2",ccc);
//		//{xsm={dddd={dddd=dddd}}}
//		Map zz = (Map) map3.get("xsm");
//		zz.put("789","000");
//		map3.put("xsm",zz);
		
	}
	
	
	
	@SuppressWarnings("rawtypes")
	public void mapped(Map map,Map nmap,String keys){
		Set set = map.keySet();
		for (Iterator it = set.iterator(); it.hasNext();) {
			String key = (String) it.next();
			
			if(keys.equals("") || key.equals("persons")){
				keys=key;
			}else{
				keys=keys+"."+key;
			}
			String toKey = PropUtil.getPropByKey("add_filed",keys);
			Object value = map.get(key);
			if (null == value)
				value = "";
			if (value.getClass().getName().equals("java.util.ArrayList")) {
				ArrayList list = (ArrayList) map.get(key);
			//	sb.append("<" + key + ">");
				for (int i = 0; i < list.size(); i++) {
				//	Object listi = list.get(i);
					if(list.get(i) instanceof HashMap){
						HashMap hm = (HashMap) list.get(i);
					//	nmap.put(toKey, value);
						mapped(hm, nmap,keys);
					}
					else{
						nmap.put(toKey,list.get(i));
					//	sb.append("<" + key + ">" + list.get(i) + "</" + key + ">");
					}
				//	else if(listi.getClass().getName().equals("java.util.ArrayList")){
				//		sb.append("<" + key + ">" + "??" + "</" + key + ">");}
					
					
				}
			//	sb.append("</" + key + ">");

			} else {
				if (value instanceof HashMap) {
				//	sb.append("<" + key + ">");
					mapped((HashMap) value, nmap,keys);
				//	sb.append("</" + key + ">");
				} else {
				//	sb.append("<" + key + ">" + value + "</" + key + ">");
					nmap.put(toKey, value);
				}

			}

		}
	}
	
	public String filedMapped(){
		
		return "";
	}
	
	
	public void tt(Map map){
		System.out.println("未转化之前:"+map);
//		for(int i=0;i<list.size();i++){
//			
//		}
		
		String fromstr="persons.person.age";
		String tostr="students.student.nl";
		String f[] = fromstr.split("\\.");
		String t[] = tostr.split("\\.");
		Map temp = map;
		String str = "";
		Object obj= map;
		String type = "";
		List tlist = null;
		Map nmap = new HashMap();
		mapped(map,nmap,"");
		System.out.println("nmap:"+nmap);
		for(int i=0;i<f.length;i++){
			
			if(obj instanceof List){
				
				
				obj=((Map<String, Object>) obj).get(f[i]);
			}
			
			if(obj instanceof Map){
				obj=((Map<String, Object>) obj).get(f[i]);
			}
			
			
			
			nmap.put(t[i],obj);
		}
		
		
//		for(int i=0;i<f.length;i++){
//			if(temp.get(f[i]) instanceof Map){
//				temp=(Map) temp.get(f[i]);
//				nmap.put(t[i], temp);
//			//	System.out.println(temp.get(f[i]));
//				type="map";
//			}else if(temp.get(f[i]) instanceof List){
//				tlist
//			}else{
//				str=(String) temp.get(f[i]);
//				nmap.put(t[i],str );
//				type="string";
//			}
//		}
		
		System.out.println("转换之后:"+nmap);
		System.out.println(type);
	}
	
	
	
	
	
	

	

}
